package com.rzn.reading.service.impl;

import com.rzn.reading.BeanMapper;
import com.rzn.reading.BusinessException;
import com.rzn.reading.GlobalExceptionHandler;
import com.rzn.reading.entity.User;
import com.rzn.reading.mapper.UserMapper;
import com.rzn.reading.model.dto.user.UpdatePasswordDTO;
import com.rzn.reading.model.dto.user.UserCreateInputDTO;
import com.rzn.reading.model.dto.user.UserInfoDTO;
import com.rzn.reading.model.dto.user.UserUpdateDTO;
import com.rzn.reading.model.param.LoginParam;
import com.rzn.reading.service.UserService;
import com.rzn.reading.utils.MD5Utils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author rzn
 * @since 2022-02-12
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserInfoDTO login(LoginParam loginParam) {
        User user = userMapper.selectByUsername(loginParam.getUsername());
        if (user==null){
            throw new BusinessException("用户尚未注册");
        }
        //如果密码错误则抛出异常
        if (!MD5Utils.matches(loginParam.getPassword(), user.getPassword())) {
            throw new BusinessException("密码错误");
        }
        UserInfoDTO userInfoDTO = BeanMapper.map(user, UserInfoDTO.class);
        return userInfoDTO;
    }

    @Override
    public Boolean register(UserCreateInputDTO userCreateInputDTO) {
        Integer rows = userMapper.existUser(userCreateInputDTO.getUsername());
        if (rows > 0) {
            throw new BusinessException("用户名已注册，请重新输入");
        }
        User user = BeanMapper.map(userCreateInputDTO,User.class);
        user.setPassword(MD5Utils.encode(user.getPassword()));
        return userMapper.insert(user) == 1;
    }

    @Override
    public Boolean updateUserInfo(UserUpdateDTO userUpdateDTO) {
        User user = BeanMapper.map(userUpdateDTO, User.class);
        return userMapper.updateByPrimaryKey(user) == 1;
    }

    @Override
    public Boolean updatePassword(UpdatePasswordDTO updatePasswordDTO) {
        updatePasswordDTO.setPassword(MD5Utils.encode(updatePasswordDTO.getPassword()));
        return userMapper.updatePassword(updatePasswordDTO)==1;
    }
}
